import os
import re
import json
import requests


# 函数：加载提示词内容
def load_prompt_seed(file_name="Fuzz/docs/prompt_seed.txt"):
    if os.path.exists(file_name):
        with open(file_name, "r", encoding="utf-8") as file:
            return file.read()
    else:
        raise FileNotFoundError(f"{file_name} 文件未找到。")

def load_prompt_all(file_name="Fuzz/docs/promptDriver.txt"):
    if os.path.exists(file_name):
        with open(file_name, "r", encoding="utf-8") as file:
            return file.read()
    else:
        raise FileNotFoundError(f"{file_name} 文件未找到。")



def get_completion(prompt):
    headers = {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer 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',
    }

    data = {
        "model": "deepseek/deepseek-chat-v3-0324:free",
        "prompt": prompt,
    }

    response = requests.post('https://openrouter.ai/api/v1/chat/completions', headers=headers, data=json.dumps(data))

    return response.json()['choices'][0]['text']

def get_driver_data(tested_func, source_code):
    # 加载提示词内容
    prompt_all = load_prompt_all()

    param_types = '''
        NumList : {
            a : int,
            b : float
       }
    '''
    prompt_content = (
            f"{prompt_all}\n\n"
            f"C# 待测函数代码：\n{source_code}\n\n"
            f"C# 待测函数参数类型：\n{param_types}\n\n"
            f"C# 函数测试用例：\n{tested_func}\n\n"
            "1. 为了防止原函数出现错误导致不能变异数据，对原函数进行注释，但请勿删除原函数"
            "2. 请针对待测函数参数类型进行变异"
            "3. 生成的代码请用以下格式包裹：```csharp\n ... \n```。保证能让 pattern = r'```csharp\s*(?:\[Fact\])?\s*(.*?)\s*```'识别"

        )
    get_num = True
    i = 0
    while get_num and i < 3:
        # 非流式输出

        model_output = get_completion(prompt_content)
        # print("输出已保存到 output.txt 文件中。")
        # 正则表达式模式，用于匹配 `csharp` 代码块
        # print(model_output)

        pattern = r'```csharp\s*(?:\[Fact\])?\s*(.*?)\s*```'


        # 使用 re.findall 提取所有匹配的内容，并指定 re.DOTALL 以匹配多行
        csharp_code_blocks = re.findall(pattern, model_output, re.DOTALL)
        print(len(csharp_code_blocks))
        if csharp_code_blocks != []:
            get_num = False
            with open("output_driver.txt", "w", encoding="utf-8") as file:
                file.write(csharp_code_blocks[0])

        i+=1
        prompt_content = (
            "生成的代码请用以下格式包裹：```csharp\n ... \n```。,保证能让 pattern = r'```csharp\s*(?:\[Fact\])?\s*(.*?)\s*```'识别"
         )
    return csharp_code_blocks[0]








